'use client';

import { useState, useEffect } from 'react';
import { useWallet } from'@/components/ui/WalletProvider';
import CardPreview from '@/components/business/CardPreview';
import CardDetail from '@/components/business/CardDetail';

export default function DeckManagement() {
  const [activeTab, setActiveTab] = useState('current'); // current, select, create
  
  const [userCards, setUserCards] = useState([]); // 用户拥有的卡牌
  const [selectedCards, setSelectedCards] = useState([]); // 选中的卡牌
  const [deckName, setDeckName] = useState(''); // 卡组名称
  const [selectedCard, setSelectedCard] = useState(null); // 当前选中的卡牌详情
  const [detailPosition, setDetailPosition] = useState({ x: 0, y: 0 }); // 详情框位置

  const { account, isConnecting, error, connectWallet, tokenContract, heroContract, battleContract,currentUser } = useWallet();

  // 获取用户卡牌
  useEffect(() => {
    const fetchUserCards = async () => {
      if (account && heroContract) {
        try {
          const [cardIds, balances, attributes] = await heroContract.getUserCards(account);
          const cards = cardIds.map((id, index) => ({
            id: id.toString(),
            balance: balances[index].toString(),
            name: attributes[index].name,
            power: attributes[index].power,
            cost: attributes[index].cost,

          }));
          setUserCards(cards);
          for (let card of cards) {
            console.log(card);
          }
        } catch (error) {
          console.error('获取卡牌失败:', error);
        }
      }
    };

    fetchUserCards();
  }, [account, heroContract]);

  // 处理卡牌选择
  const handleCardSelect = (card) => {
    setSelectedCards(prev => {
      const isSelected = prev.some(c => c.id === card.id);
      if (isSelected) {
        return prev.filter(c => c.id !== card.id);
      } else if (prev.length < 12) { // 限制卡组最多12张卡
        return [...prev, card];
      }
      return prev;
    });
  };

  // 处理卡组创建
  const [isCreating, setIsCreating] = useState(false);

  const handleDeckCreate = async () => {
    if (!account || !heroContract || !deckName.trim() || selectedCards.length === 0 || !currentUser) return;
    
    setIsCreating(true);
    try {
      const cardIds = selectedCards.map(card => card.id);
      
      const response = await fetch('/api/deck/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: currentUser,
          name: deckName.trim(),
          cards: cardIds
        })
      });

      if (!response.ok) {
        throw new Error('创建卡组失败');
      }

      const result = await response.json();
      console.log('创建成功:', result);
      alert('卡组创建成功');
      setDeckName('');
      setSelectedCards([]);
    } catch (error) {
      console.error('创建卡组失败:', error);
      alert(error.message || '创建卡组失败，请稍后重试');
    } finally {
      setIsCreating(false);
    }
  }

  const renderCurrentDeck = () => (
    <div className="bg-white p-6 rounded-lg shadow">
      <h2 className="text-2xl font-bold text-gray-900 mb-6">当前卡组</h2>
      <div className="grid grid-cols-4 gap-4">
        {/* TODO: 显示当前卡组中的卡牌 */}
      </div>
    </div>
  );

  const renderSelectDeck = () => (
    <div className="bg-white p-6 rounded-lg shadow">
      <h2 className="text-2xl font-bold text-gray-900 mb-6">选择卡组</h2>
      <div className="grid grid-cols-3 gap-6">
        {/* TODO: 显示所有可选卡组 */}
      </div>
    </div>
  );

  const renderCreateDeck = () => (
    <div className="bg-white p-6 rounded-lg shadow">
      <h2 className="text-2xl font-bold text-gray-900 mb-6">创建卡组</h2>
      <div className="space-y-6">
        <input
          type="text"
          placeholder="卡组名称"
          value={deckName}
          onChange={(e) => setDeckName(e.target.value)}
          className="w-full p-2 border rounded"
        />
        <div className="mb-6 bg-gray-50 p-4 rounded-lg shadow-sm">
          <h3 className="text-lg font-semibold mb-3 flex items-center justify-between">
            <span>已选择的卡牌</span>
            <span className="text-sm font-normal text-gray-600">({selectedCards.length}/12)</span>
          </h3>
          <div className="grid grid-cols-6 gap-3">
            {selectedCards.map(card => (
              <div
                key={card.id}
                onClick={() => handleCardSelect(card)}
                className="relative group border border-blue-200 p-2 rounded-lg cursor-pointer bg-white hover:bg-blue-50 hover:border-blue-400 transition-all duration-200 text-sm"
              >
                <div className="flex items-center justify-between gap-2">
                  <span className="truncate flex-1">{card.name}</span>
                  <span className="text-blue-600 font-medium">{card.cost}</span>
                </div>
                <div className="absolute -top-2 -right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button className="bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs hover:bg-red-600">
                    ×
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="grid grid-cols-4 gap-4 relative">
          {selectedCard && (
            <div
              style={{
                position: 'fixed',
                left: `${detailPosition.x}px`,
                top: `${detailPosition.y}px`,
                transform: `translate(20px, ${detailPosition.y + 400 > window.innerHeight ? '-100%' : '0'})`,
                maxHeight: '80vh',
                overflowY: 'auto',
                zIndex: 50
              }}
            >
              <CardDetail card={selectedCard} />
            </div>
          )}
          {userCards.map(card => (
            <CardPreview
              key={card.id}
              card={card}
              onClick={handleCardSelect}
              onShowDetail={(card, position) => {
                setDetailPosition(position);
                setSelectedCard(card);
              }}
              onHideDetail={() => setSelectedCard(null)}
              isSelected={selectedCards.some(c => c.id === card.id)}
            />
          ))}
        </div>
        <button 
          className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700 transition-colors disabled:bg-blue-400 disabled:cursor-not-allowed"
          disabled={selectedCards.length === 0 || !deckName.trim() || isCreating}
          onClick={handleDeckCreate}
        >
          {isCreating ? '创建中...' : '创建卡组'}
        </button>
      </div>
    </div>
  );

  return (
    <div className="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
      {selectedCard && <CardDetail card={selectedCard} onClose={() => setSelectedCard(null)} />}
      <div className="max-w-7xl mx-auto">
        <div className="flex space-x-4 mb-8">
          <button
            onClick={() => setActiveTab('current')}
            className={`px-6 py-2 rounded-lg ${activeTab === 'current' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700'}`}
          >
            当前卡组
          </button>
          <button
            onClick={() => setActiveTab('select')}
            className={`px-6 py-2 rounded-lg ${activeTab === 'select' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700'}`}
          >
            选择卡组
          </button>
          <button
            onClick={() => setActiveTab('create')}
            className={`px-6 py-2 rounded-lg ${activeTab === 'create' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700'}`}
          >
            创建卡组
          </button>
        </div>

        {activeTab === 'current' && renderCurrentDeck()}
        {activeTab === 'select' && renderSelectDeck()}
        {activeTab === 'create' && renderCreateDeck()}
      </div>
    </div>
  );
}